#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/26 22:01
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : token.py
# @Software: PyCharm
# @Desc    : Token的curd

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.generics import GenericAPIView

from common.fiters.filter_token import TokenFilter
from common.models import Token
from common.sers.ser_token import TokenSerializer
from common.utils.pagination import EnhancedPageNumberPagination
from common.utils.rsp import success_response
from common.utils.utils_token import TokenUtils


class TokenListCreateView(GenericAPIView):
    """
    Token列表查询 + 新增接口
    - GET: 分页查询Token列表（支持过滤、排序）
    - POST: 新增Token（自动生成JWT）
    """
    queryset = Token.objects.filter(is_delete=0, pt_flag=0).all()
    serializer_class = TokenSerializer
    pagination_class = EnhancedPageNumberPagination
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = TokenFilter
    ordering_fields = ["create_time", "name", "expires_time"]
    ordering = ["-create_time"]

    def get(self, request, *args, **kwargs):
        """分页查询Token列表"""
        filtered_qs = self.filter_queryset(self.get_queryset())
        page_qs = self.paginate_queryset(filtered_qs)
        serializer = self.get_serializer(page_qs, many=True)
        paginated_data = self.paginator.get_paginated_response(serializer.data).data
        return success_response(data=paginated_data, message="Token列表查询成功")

    def post(self, request, *args, **kwargs):
        """新增Token（自动生成JWT）"""
        creator = TokenUtils.get_creator_info(request)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(
            data=serializer.data,
            message=f"Token「{serializer.validated_data.get('name')}」创建成功"
        )


class TokenRetrieveUpdateDestroyView(GenericAPIView):
    """
    Token单条操作接口
    - GET: 查询详情
    - PUT/PATCH: 更新Token（不允许修改token字段）
    - DELETE: 逻辑删除
    """
    queryset = Token.objects.all()
    serializer_class = TokenSerializer
    lookup_field = "pk"

    def get_object(self):
        """只允许操作有效Token"""
        instance = super().get_object()
        if instance.is_delete == 1 or instance.pt_flag == 1:
            raise ValueError("Token不存在或已被删除")
        return instance

    def get(self, request, *args, **kwargs):
        """查询Token详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(data=serializer.data, message="Token详情查询成功")

    def put(self, request, *args, **kwargs):
        """全量更新（不允许修改token字段）"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=False)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(
            data=serializer.data,
            message=f"Token「{instance.name}」更新成功"
        )

    def patch(self, request, *args, **kwargs):
        """部分更新（不允许修改token字段）"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(
            data=serializer.data,
            message=f"Token「{instance.name}」部分更新成功"
        )

    def delete(self, request, *args, **kwargs):
        """逻辑删除Token"""
        instance = self.get_object()
        instance.is_delete = 1
        instance.save()
        return success_response(
            data=None,
            message=f"Token「{instance.name}」已删除"
        )
